package com.hippo.client.controller.nacos;

import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ClassName DiscoveryController
 * @Description TODO nacos服务发现
 * @Author tangxl
 * @create 2023-03-23 15:49
 **/
@RestController
@RequestMapping("/discovery")
public class DiscoveryController {

    @Value("${spring.cloud.nacos.discovery.server-addr}")
    private String serverAddr;

    @NacosInjected // 使用nacos client的NacosInjected注解注入服务
    private NamingService namingService;

    /**
     * 注册服务
     * @param serviceName
     * @return
     * @throws NacosException
     */
    @GetMapping("/set")
    public String set(@RequestParam String serviceName) throws NacosException {
        try {
            namingService.registerInstance(serviceName, serverAddr.split(":")[0], Integer.parseInt(serverAddr.split(":")[1])); // 注册中心的地址
            return "OK";
        } catch (NacosException e) {
            e.printStackTrace();
            return "ERROR";
        }
    }

    @GetMapping(value = "/get")
    public List<Instance> get(@RequestParam String serviceName) throws NacosException {
        return namingService.getAllInstances(serviceName);
    }

    /**
     * 获取nacos中所有注册的服务
     * @return
     * @throws NacosException
     */
    @GetMapping(value = "/getAll")
    public List<Instance> get() throws NacosException {
        return null;
    }
}
